package cn.zxf.note.note.type;

import cn.zxf.note.common.jpa.AbstractDao;
import cn.zxf.note.note.type.dto.NoteTypeStatisticsDto;
import com.github.zengxf.common.utils.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class NoteTypeDao extends AbstractDao {

    public List<NoteTypeStatisticsDto> statistics(Integer userId) {
        String sql = "WITH \n" + //
                "nt AS (SELECT id, name FROM note_type WHERE user_id = :uid AND status = :status), \n" + //
                "n  AS (SELECT COUNT(*) number, type_id FROM note WHERE user_id = :uid AND status = :status GROUP BY type_id) \n" + //
                "SELECT id, name, number note_number FROM nt LEFT JOIN n ON nt.id = n.type_id ORDER BY id DESC";
        log.debug("sql: {}", sql);
        Map map = Map.of(
                "uid", userId,
                "status", NoteTypeStatusEnum.NORMAL.code
        );
        RowMapper<NoteTypeStatisticsDto> rm = BeanPropertyRowMapper.newInstance(NoteTypeStatisticsDto.class);
        return super.namedJdbc.query(sql, map, rm);
    }

    public NoteType findByName(Integer userId, String name) {
        String sql = "SELECT * FROM note_type WHERE user_id = :uid AND status = :status AND name = :name";
        Map map = Map.of(
                "uid", userId,
                "status", NoteTypeStatusEnum.NORMAL.code,
                "name", name
        );
        RowMapper<NoteType> rm = BeanPropertyRowMapper.newInstance(NoteType.class);
        List<NoteType> list = super.namedJdbc.query(sql, map, rm);
        return ListUtils.one(list);
    }

}
